package org.etlt.op.ud;

import org.apache.commons.lang3.StringUtils;
import org.etlt.expression.VariableContext;
import org.etlt.expression.function.FunctionActor;
import org.etlt.expression.function.FunctionEnabled;
import org.etlt.job.JobContext;

import java.util.Map;
import java.util.Objects;

@FunctionEnabled(value = "mapping", help = "if mapped value is null, return the key as returned value")
public class Mapping implements FunctionActor {

    @Override
    public Object operate(VariableContext context, Object... args) {
        checkArgs(args);
        String catalog = args[0].toString();
        if (args[1] == null) {
            return args.length > 2 ? args[2] : null;
        }
        String key = args[1].toString();
        Map<String, Object> mappedValues = ((JobContext) context).getMapping();
        if (StringUtils.isBlank(catalog))
            throw new IllegalArgumentException("catalog name of mapping cannot be blank.");
        if (StringUtils.isBlank(key))
            return key;
        Map cmap = ((Map) mappedValues.get(catalog));
        if (Objects.isNull(cmap))
            throw new IllegalArgumentException("catalog of mapping missing, check mapping configuration: " + catalog);
        Object mappedValue = cmap.get(key.trim());
//        if (mappedValue != null)
//            return mappedValue;
        if (cmap.containsKey(key.trim()))
            return mappedValue;
        else
            return (mappedValue == null && args.length > 2) ?
                    args[2] :
                    key;
    }

    @Override
    public void checkArgs(Object... args) {
        if (args.length < 2) {
            throw new IllegalArgumentException("mapping function need 2 argument at least: mapping catalog , mapping key and possible default value");
        }
    }
}
